package com.icedevcloud.gateway.config;

import cn.dev33.satoken.reactor.context.SaReactorSyncHolder;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.icedevcloud.gateway.config.properties.IgnoreUrlsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;

import java.util.HashMap;

/**
 * <p>
 * [Sa-Token 权限认证] 配置类
 * </p>
 *
 * @author dengbing
 * @since 2023-08-24
 */
@Configuration
public class AuthConfigure {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Bean
    public SaReactorFilter getSaReactorFilter(IgnoreUrlsProperties ignore) {
        return new SaReactorFilter()
                // 拦截地址
                .addInclude("/**")
                // 鉴权方法：每次访问进入
                .setAuth(obj -> {
                    // 登录校验 -- 拦截所有路由
                    SaRouter.match("/**")
                            .notMatch(ignore.getUrls())
                            .check(r -> StpUtil.checkLogin());
                }).setError(e -> {
                    ServerWebExchange context = SaReactorSyncHolder.getContext();
                    context.getResponse().setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
                    context.getResponse().getHeaders().add("Content-Type", "application/json;charset=UTF-8");

                    HashMap<String, Object> resultMap = new HashMap<>();
                    resultMap.put("code", 401);
                    resultMap.put("message", "认证失败，无法访问系统资源");
                    resultMap.put("data", null);
                    try {
                        return objectMapper.writeValueAsString(resultMap);
                    } catch (JsonProcessingException ex) {
                        throw new RuntimeException(ex);
                    }
                });
    }

}
